// API基础URL
const API_BASE_URL = 'http://localhost:8080/api/workers';

// DOM元素
const addWorkerForm = document.getElementById('addWorkerForm');
const workersContainer = document.getElementById('workersContainer');
const messageContainer = document.getElementById('messageContainer');
const totalWorkers = document.getElementById('totalWorkers');
const totalClassrooms = document.getElementById('totalClassrooms');
const totalTeachers = document.getElementById('totalTeachers');
const logoutBtn = document.getElementById('logoutBtn');
const usernameDisplay = document.getElementById('usernameDisplay');

// 显示消息
function showMessage(message, isSuccess = true) {
    messageContainer.innerHTML = `
        <div class="message ${isSuccess ? 'success' : 'error'}">
            ${message}
        </div>
    `;

    setTimeout(() => {
        messageContainer.innerHTML = '';
    }, 5000);
}

// 获取所有工人
async function fetchWorkers() {
    try {
        const response = await fetch(API_BASE_URL);
        if (!response.ok) {
            throw new Error('获取工人列表失败');
        }
        return await response.json();
    } catch (error) {
        console.error('获取工人列表失败:', error);
        showMessage('获取工人列表失败: ' + error.message, false);
        return [];
    }
}

// 更新统计信息
function updateStats(workers) {
    totalWorkers.textContent = workers.length;

    // 计算唯一教室数量
    const classrooms = new Set(workers.map(worker => worker.classroom));
    totalClassrooms.textContent = classrooms.size;

    // 计算唯一老师数量
    const teachers = new Set(workers.map(worker => worker.teacher));
    totalTeachers.textContent = teachers.size;
}

// 渲染工人列表
function renderWorkers(workers) {
    if (workers.length === 0) {
        workersContainer.innerHTML = '<div class="no-data">暂无工人数据</div>';
        return;
    }

    workersContainer.innerHTML = '';
    workers.forEach(worker => {
        const workerCard = document.createElement('div');
        workerCard.className = 'worker-card';
        workerCard.innerHTML = `
            <div class="worker-header">
                <div class="worker-name">${worker.name}</div>
                <div class="worker-id">ID: ${worker.id}</div>
            </div>
            <div class="worker-details">
                <div class="detail-row">
                    <span class="detail-label">教室号</span>
                    <span class="detail-value">${worker.classroom}</span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">老师</span>
                    <span class="detail-value">${worker.teacher}</span>
                </div>
                <div class="detail-row">
                    <span class="detail-label">日期</span>
                    <span class="detail-value">${worker.date}</span>
                </div>
            </div>
            <div class="worker-actions">
                <button class="btn btn-primary btn-edit" data-id="${worker.id}">
                    <i class="fas fa-edit"></i> 编辑
                </button>
                <button class="btn btn-danger btn-delete" data-id="${worker.id}">
                    <i class="fas fa-trash"></i> 删除
                </button>
            </div>
        `;
        workersContainer.appendChild(workerCard);
    });

    // 添加编辑事件监听
    document.querySelectorAll('.btn-edit').forEach(btn => {
        btn.addEventListener('click', () => {
            const workerId = btn.getAttribute('data-id');
            editWorker(workerId);
        });
    });

    // 添加删除事件监听
    document.querySelectorAll('.btn-delete').forEach(btn => {
        btn.addEventListener('click', () => {
            const workerId = btn.getAttribute('data-id');
            deleteWorker(workerId);
        });
    });
}

// 添加工人
addWorkerForm.addEventListener('submit', async (e) => {
    e.preventDefault();

    const worker = {
        name: document.getElementById('name').value,
        classroom: parseInt(document.getElementById('classroom').value),
        teacher: document.getElementById('teacher').value
    };

    try {
        const response = await fetch(API_BASE_URL, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(worker)
        });

        if (!response.ok) {
            throw new Error('添加工人失败');
        }

        const createdWorker = await response.json();
        showMessage(`工人 ${createdWorker.name} 添加成功`);
        addWorkerForm.reset();
        refreshWorkers();
    } catch (error) {
        console.error('添加工人失败:', error);
        showMessage('添加工人失败: ' + error.message, false);
    }
});

// 编辑工人
async function editWorker(workerId) {
    const newName = prompt('请输入新的姓名:');
    if (newName) {
        try {
            // 先获取当前工人信息
            const response = await fetch(`${API_BASE_URL}/${workerId}`);
            if (!response.ok) {
                throw new Error('获取工人信息失败');
            }

            const worker = await response.json();

            // 更新工人信息
            worker.name = newName;

            const updateResponse = await fetch(`${API_BASE_URL}/${workerId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(worker)
            });

            if (!updateResponse.ok) {
                throw new Error('更新工人失败');
            }

            showMessage('工人信息更新成功');
            refreshWorkers();
        } catch (error) {
            console.error('编辑工人失败:', error);
            showMessage('编辑工人失败: ' + error.message, false);
        }
    }
}

// 删除工人
async function deleteWorker(workerId) {
    if (!confirm('确定要删除这个工人吗？')) return;

    try {
        const response = await fetch(`${API_BASE_URL}/${workerId}`, {
            method: 'DELETE'
        });

        if (!response.ok) {
            throw new Error('删除工人失败');
        }

        showMessage('工人删除成功');
        refreshWorkers();
    } catch (error) {
        console.error('删除工人失败:', error);
        showMessage('删除工人失败: ' + error.message, false);
    }
}

// 刷新工人列表
async function refreshWorkers() {
    workersContainer.innerHTML = '<div class="no-data">加载中...</div>';
    const workers = await fetchWorkers();
    updateStats(workers);
    renderWorkers(workers);
}

// 退出登录
logoutBtn.addEventListener('click', () => {
    localStorage.removeItem('user');
    window.location.href = 'login.html';
});

// 初始化页面
document.addEventListener('DOMContentLoaded', () => {
    const user = JSON.parse(localStorage.getItem('user'));
    if (!user) {
        // 如果未登录，跳转到登录页面
        window.location.href = 'login.html';
        return;
    }

    // 显示用户名
    usernameDisplay.textContent = user.username;

    // 刷新工人列表
    refreshWorkers();

    // 添加导航点击事件
    document.querySelectorAll('.nav-item').forEach(item => {
        item.addEventListener('click', function() {
            document.querySelectorAll('.nav-item').forEach(i => i.classList.remove('active'));
            this.classList.add('active');
        });
    });
});